package org.i_plus.model.services;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.hibernate.SessionFactory;
import org.i_plus.model.BlogBean;
import org.i_plus.model.HobbyBean;
import org.i_plus.model.MemberBean;
import org.i_plus.model.TarotBean;
import org.i_plus.model.TarotDAO;
import org.i_plus.model.dao.BlogDAOHibernate;
import org.i_plus.model.dao.HobbyDAOHibernate;
import org.i_plus.model.dao.MemberDAOHibernate;
import org.i_plus.model.dao.TarotDAOHibernate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@Path("/memberService")
public class MemberService {

	private MemberDAOHibernate dao = null;
	private MessageDigest md;
	private HobbyDAOHibernate hdao ;
	private TarotDAO tdao ;
	private BlogDAOHibernate bdao;
	public void setMemberDAO(MemberDAOHibernate dao){
		this.dao = dao;
		try {
			this.md = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}
	public void setHobbyDAO(HobbyDAOHibernate hdao){
		this.hdao = hdao;
	}
	public void setTarotDAO(TarotDAOHibernate tdao){
		this.tdao = tdao;
	}
	public void setBlogDAO(BlogDAOHibernate bdao) {
		this.bdao = bdao;
	}
	
	public MemberBean select_by_account(String account)
	{
		MemberBean bean=dao.Select_By_Account(account);
		return bean;
	}
	public HobbyBean selectHobby(String account)
	{
		HobbyBean hbean=hdao.selectByAccount(account);
		if(hbean!=null)
		{
			return hbean;
		}
		return null;
	}
	public List<BlogBean> select_blog_by_account(String account)
	{
		List<BlogBean> result=bdao.selectbyAcc(account);
		return result;
	}
	
//登入	
public MemberBean login(String account,String password){
	MemberBean bean = dao.Select_By_Account(account);
	if(bean!=null) {
		if(password!=null && password.length()!=0) {
			byte[] pass = password.getBytes();	//明碼
			pass = md.digest(pass);    //把使用者的密碼轉成暗碼
			byte[] temp = bean.getPwd();	//暗碼
			if(Arrays.equals(pass, temp)) {
				return bean;
			}
		}
	}
	return null;
	}
//修改密碼
public boolean changePassword(
		String username, String oldPassword, String newPassword) {
	MemberBean bean = this.login(username, oldPassword);
	//newPassword.matches(regex);
	if(bean!=null) {
		byte[] temp = newPassword.getBytes();//明碼
		temp = md.digest(temp);                          //轉成暗碼
		dao.Update(bean.getAccount(), temp,
				bean.getName(), bean.getNickname(), bean.getPic1(), bean.getPic2(),
				bean.getSex(), bean.getBdate(), bean.getHight(), bean.getRegion(),
				bean.getBlood(), bean.getState(), bean.getPop(), bean.getBonus(),
				bean.getHobby(), bean.getMlike(), bean.getPlay(), bean.getTarot(),
				bean.getMkind(), bean.getCheckvip());
		return true;
	}
	return false;
}

   //註冊
public void insertMember(MemberBean bean)
{
	try {
		md = MessageDigest.getInstance("MD5");
	} catch (NoSuchAlgorithmException e) {
		e.printStackTrace();
	}
	byte[] temp = md.digest(bean.getPwd());
	bean.setPwd(temp);
	dao.insert(bean);
}
public void insertHobby(HobbyBean bean)
{
	hdao.insert(bean);
}
public void updateMember(MemberBean bean)
{
	dao.Updateall(bean);
}
public void updateHobby(HobbyBean bean)
{
	hdao.update(bean);
}
    //後台 選取所有會員 加上分頁功能
    public List<MemberBean> selectAll(int page){
    	return dao.findMany(page, "from MemberBean as member") ;
    }
   //配對搜尋 使用stored procedure
    public List matchByProcedure(int page,String region,String sex,int hight,
			  String blood,String mstate,boolean play,
			  boolean ball,boolean run,boolean reading,
			  boolean swim,boolean movie,
			  boolean singing,boolean bike,
			  boolean tvgame,String constellation
				){
    	List result = new ArrayList();//第一個放總頁數 第二個才放原始資料
    	result.add(dao.callStoredProcedureMatchPages
    			(region, sex, hight, blood, mstate, play, ball, 
    					run, reading, swim, movie, singing, bike, tvgame,constellation));
    	List<MemberBean> beans = dao.callStoredProcedureMatch
    			(page, region, sex, hight, blood, mstate, play, ball, run, 
    					reading, swim, movie, singing, bike, tvgame,constellation);
    	result.add(beans);
    	return result;
    }
    //搜尋抽哪張tarot
    public TarotBean checkTarot(String account){
    	MemberBean bean = dao.Select_By_Account(account);
    	int tarot = bean.getTarot();
    	return tdao.selectT(tarot);
    }
   
    //抽塔羅牌
    @GET  
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes("application/json")
    public TarotBean insertTarot(@QueryParam("account") String account,@QueryParam("tarot") int tarot){
    	ApplicationContext context = new ClassPathXmlApplicationContext("beans.config.xml");
		TarotDAO tdao = (TarotDAO)context.getBean("tarotDAO");
		MemberDAOHibernate mdao = (MemberDAOHibernate)context.getBean("MemberDAO");
    	SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    	sessionFactory.getCurrentSession().beginTransaction();
    	
    	MemberBean bean = mdao.Select_By_Account(account);//先查此帳號的tarot
    	mdao.Update(bean.getAccount(), bean.getPwd(), bean.getName(), bean.getNickname(),//update tarot
    			bean.getPic1(), bean.getPic2(), bean.getSex(), bean.getBdate(), bean.getHight(),
    			bean.getRegion(), bean.getBlood(), bean.getState(), bean.getPop(), bean.getBonus(),
    			bean.getHobby(), bean.getMlike(), bean.getPlay(), tarot, bean.getMkind(), bean.getCheckvip());
    	
    	TarotBean result = tdao.selectT(tarot);
    	sessionFactory.getCurrentSession().getTransaction().commit();
    	return result;//select 結果
    }
    
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.config.xml");
		MemberService service = (MemberService)context.getBean("MemberService");
    	SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
    	sessionFactory.getCurrentSession().beginTransaction();
    	//以下測試
//    	Set<MemberBean> members = service.match(1, null, "m", 0, "a", null, false, false,
//    																						true, false, false, true, false, true, true);
//    																					//ball,run,reading,swim,movie,singing,bike,tvgame,constellation
//    	System.out.println(members);
//    	for(MemberBean temp:members)
//    		System.out.println(temp.getAccount());
    	
//    	List<Object> result = service.matchByProcedure(1, null, "m", 0, "a", null, false, false,
//    																						true, false, false, true, false, true, true,"魔羯");
//    																					//ball,run,reading,swim,movie,singing,bike,tvgame,constellation
//    	System.out.println(result.get(0));
//    	for(MemberBean temp:(List<MemberBean>)result.get(1))
//    		System.out.println(temp.getAccount());
//    	TarotBean bean = service.checkTarot("a19897811");
//    	System.out.println(bean);
    	System.out.println(service.changePassword("a19897811", null, "24563285s"));
    	
    	MemberBean bean = service.login("a19897811", null);
    	System.out.println(bean);
		//以上測試
		sessionFactory.getCurrentSession().getTransaction().commit();
	}

}
